package com.dumovie.message.sms;

import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.text.MessageFormat;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;

/**
 * @author kim 2015年6月23日
 */
public class SmsContext {

	private final static Log LOGGER = LogFactory.getLog(SmsContext.class);

	private final static String USER = "J23080";

	private final static String PASS = "187008";

	private final String url = "http://218.204.222.12:7903/MWGate/wmgw.asmx/MongateCsSpSendSmsNew?userId={0}&amp;password={1}&amp;pszMobis={2}&amp;iMobiCount={4}&amp;pszSubPort=*&amp;pszMsg={3}";

	private final String recommendUrl = "http://sms.pica.com/zqhdServer/sendSMS.jsp?regcode=PAPH-CRM-0100-JMFMBO&pwd=c45a72956c9b0b40332fa49dafc1f98d&phone={0}&CONTENT={1}&extnum=&level=1&schtime=&reportflag=0&url=&smstype=4&hardKEY=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
	private final String checkUrl = "http://sms.pica.com/zqhdServer/getreport.jsp?regcode=PAPH-CRM-0100-JMFMBO&pwd=c45a72956c9b0b40332fa49dafc1f98d&hardKEY=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
	public SmsContext() {
		super();
		// this.url = url;
	}

	public void send(SmsMessage message) {
		try (InputStream input = new URL(MessageFormat.format(this.url,
				SmsContext.USER, SmsContext.PASS, SmsMessage.class
						.cast(message).getTargetsAsString(), URLEncoder.encode(
						message.getContent(), "UTF-8"), message.getTargets()
						.size())).openStream()) {
			IOUtils.toString(input);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
	}

	/**
	 * 发送推广短信
	 * 
	 * @param message
	 */
	public String sendRecommended(SmsMessage message) {
		try {
			String u = MessageFormat.format(this.recommendUrl,
					SmsMessage.class.cast(message).getTargetsAsString(),
					URLEncoder.encode(message.getContent(), "GBK"));
			InputStream input = new URL(u).openStream();
			String s = IOUtils.toString(input);
			return s;
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
		
		return "failed";
	}
	
	public String checkRecommendedResult() {
		try {
			String u = this.checkUrl;
			InputStream input = new URL(u).openStream();
			String s = IOUtils.toString(input);
			return s;
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
		return "failed";
	}
}
